<?php
    /**
     * Initialize the update checker
     */
//    require get_template_directory().'/theme-updates/theme-update-checker.php';
//    $example_update_checker = new ThemeUpdateChecker(
//        'couponX',
//        'http://www.mostcoupon.com/couponx_version/info.json'
//    );
	/**
	 * =====================================================================
	 * Load Theme specific-settings
	 */
	load_template(trailingslashit(get_template_directory()) . 'inc/load_sidebars.php');
	load_template(trailingslashit(get_template_directory()) . 'inc/load_widgets.php');
	load_template(trailingslashit(get_template_directory()) . 'inc/load_custom_scripts.php');
	load_template(trailingslashit(get_template_directory()) . 'inc/load_custom_tables.php');
	load_template(trailingslashit(get_template_directory()) . 'inc/load_metadatas.php');
	load_template(trailingslashit(get_template_directory()) . 'inc/load_custom-post-types.php');
    load_template(trailingslashit(get_template_directory()) . 'inc/load_schedules.php');


	/**
	 * REDIRECT OUTLINK
	 */
    // update outlink hit count
    function cpx_update_outlink_hit_count($table_name, $mask, $cp_id = 0)
    {
        global $wpdb;
        $qr_update_hitcount = "UPDATE $table_name SET hitcount = CONCAT(hitcount + 1) WHERE mask ='$mask'";
        $wpdb->query($qr_update_hitcount);
    }
    // get aff store link by coupon id
    function cpx_get_aff_store_link($cp_id)
    {
        global $wpdb;
        $qr = "
        SELECT meta_value AS 'aff_link' FROM {$wpdb->postmeta} WHERE meta_key = 'aff_url_store_metadata' AND post_id =
        (SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = $cp_id AND meta_key = 'store_coupon_metadata');
        ";
        $obj = $wpdb->get_row($qr, object);
        return $obj->aff_link;
    }
    if(!is_admin())
	   add_action('init', 'cpx_redirect');
	function cpx_redirect()
	{
		if (get_option('test_in_localhost') == 1)
		{
			$store_prefix = get_option('aff_out_link_prefix');
            $coupon_prefix = get_option('aff_out_link_prefix_cp');
			$request = $_SERVER['REQUEST_URI'];
			$request_arr = explode('/', $request);

			if ($request_arr[2] == $store_prefix)
			{
				global $wpdb;
				$table_name = $wpdb->prefix . 'outlink';
				$mask = $request_arr[3];
                // update hit count
                cpx_update_outlink_hit_count($table_name, $mask);

				$target_obj = $wpdb->get_row("select target from $table_name where mask = '{$mask}'", object);
				$target = $target_obj->target;
				if ($target)
					wp_redirect($target, 301);
				exit;
			}
            else if($request_arr[2] == $coupon_prefix)
            {
                $aff_store = cpx_get_aff_store_link((int)$request_arr[3]);
                if($aff_store)
                    wp_redirect($aff_store, 301);
                exit;
            }
		}
		else
			if (get_option('test_in_localhost') == 0)
			{
				$store_prefix = get_option('aff_out_link_prefix');
                $coupon_prefix = get_option('aff_out_link_prefix_cp');
				$request = $_SERVER['REQUEST_URI'];
				$request_arr = explode('/', $request);
				if ($request_arr[1] == $store_prefix)
				{
					global $wpdb;
					$table_name = $wpdb->prefix . 'outlink';
					$mask = $request_arr[2];
                    // update hit count
                    cpx_update_outlink_hit_count($table_name, $mask);

					$target_obj = $wpdb->get_row("select target from $table_name where mask = '{$mask}'", object);
					$target = $target_obj->target;
					if ($target)
						wp_redirect($target, 301);
					exit;
				}
                else if($request_arr[1] == $coupon_prefix)
                {
                    $aff_store = cpx_get_aff_store_link((int)$request_arr[2]);
                    if($aff_store)
                        wp_redirect($aff_store, 301);
                    exit;
                }
			}
	}
	/**
	 * GET OUTLINK BY ID
	 */
	function cpx_get_outlink($id)
	{
		global $wpdb;
		$table_name = $wpdb->prefix . 'outlink';
		$query = "select mask from {$table_name} where id = $id";
		$mask_obj = $wpdb->get_row($query, object);
		if ($mask_obj)
		{
			return home_url('/') . get_option('aff_out_link_prefix') . '/' . $mask_obj->mask;
		}
		else
			return false;
	}
	/**
	 * GET CURRENT URL
	 * @return URL
	 */
	function cpx_current_url()
	{
		$pageURL = 'http';
		if ($_SERVER["HTTPS"] == "on")
		{
			$pageURL .= "s";
		}
		$pageURL .= "://";
		if ($_SERVER["SERVER_PORT"] != "80")
		{
			$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
		}
		else
		{
			$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
		}
		return $pageURL;
	}
	/**
	 * GET STORE THUMBNAIL
	 * @return HTML image
	 */
	function cpx_get_store_thumb($store_homepage, $w = '', $h = '')
	{
		if ($store_homepage)
		{
            if($w && $h)
                $size = "?w=$w&h=$h";
			$snap = "http://s.wordpress.com/mshots/v1/";
			return $snap . $store_homepage . $size;
		}
	}
	/**
	 * CHECK USER VOTED COUPON
	 * @return boolean
	 */
	function cpx_is_voted($coupon_id)
	{
		$current_ip = $_SERVER['REMOTE_ADDR'];
		$ip_address_voted = get_post_meta($coupon_id, 'ip_voted', true);
		$is_voted = false; // is voted ? if false then display rate coupon
		if ($ip_address_voted)
		{
			$arr_ip = explode('|', $ip_address_voted);
			if (in_array($current_ip, $arr_ip))
				$is_voted = true;
		}
		return $is_voted;
	}

	/**
	 * Calculate coupon rate
	 * @return int
	 */
	function cpx_calculate_coupon_rate($like, $dislike)
	{
		$rate = round(($like / ($like + $dislike)) * 100, 0);
		return $rate;
	}
	/**
	 * GET EMAILS FOLLOW STORE
	 */
	function cpx_get_the_ID($post_name, $post_type)
	{
		global $wpdb;
		$query = "select ID from {$wpdb->posts} where post_name = '{$post_name}' and post_type = '{$post_type}' and post_status = 'publish'";
		$result = $wpdb->get_results($query);
		return $result[0]->ID;
	}
	/**
	 * CALCULATE WEBSITE LOADING TIME
	 */
	function cpx_cal_loading_time()
	{
		//if (current_user_can('administrator'))
		//{
			global $wpdb;
			// Get the total page generation time
			$totaltime = timer_stop(false, 22);
			// Calculate the time spent on MySQL queries by adding up the time spent on each query
			$mysqltime = 0;
			// if there are indeed mysql queries then
			if ($wpdb->queries != null)
				foreach ($wpdb->queries as $query)
					$mysqltime = $mysqltime + $query[1];
			// The time spent on PHP is the remainder
			$phptime = $totaltime - $mysqltime;
			// Create the percentages
			$mysqlper = number_format_i18n($mysqltime / $totaltime * 100, 2);
			$phpper = number_format_i18n($phptime / $totaltime * 100, 2);
			// Output the stats
			//echo 'Page generated in ' . number_format_i18n($totaltime, 4) . " seconds ( {$phpper}% PHP, {$mysqlper}% MySQL )";
            echo 'Page generated in ' . number_format_i18n($totaltime, 4) . " seconds";
		//}
	}
	//word limit
	function truncate_str($str, $maxlen, $end_char = '&#8230;')
	{
		if (strlen($str) <= $maxlen)
			return $str;

		$newstr = substr($str, 0, $maxlen);
		if (substr($newstr, -1, 1) != ' ')
			$newstr = substr($newstr, 0, strrpos($newstr, " "));

		return $newstr . $end_char;
	}
	/**
	 * ADD KEYWORD TO STORE SLUG
	 */
	function append_slug($data)
	{
		global $post_ID;
		if (!empty($data['post_name']) && $data['post_type'] == 'store')
		{

            if(get_option('store_slug'))
                $new_store_slug = $data['post_title'] . '-' . get_option('store_slug');
            else
                $new_store_slug = $data['post_title'] . '-' . 'coupons';
			$data['post_name'] = sanitize_title($new_store_slug, $post_ID);
		}
		return $data;
	}
    if(is_admin())
	   add_filter('wp_insert_post_data', 'append_slug', 10);

    /**
     * GET TOP RATE COUPON BY STORE
     */
    function cpx_get_top_cp_rate($st_id, $limit = 1)
    {
        global $wpdb;
        $query = "
        SELECT
        SQL_CALC_FOUND_ROWS {$wpdb->posts}.ID
        FROM
            {$wpdb->posts}
            INNER JOIN {$wpdb->postmeta}
                ON (
                    {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id
                )
            INNER JOIN {$wpdb->postmeta} AS mt1
                ON ({$wpdb->posts}.ID = mt1.post_id)
            INNER JOIN {$wpdb->postmeta} AS mt2
                ON ({$wpdb->posts}.ID = mt2.post_id)
            INNER JOIN {$wpdb->postmeta} AS mt3
                ON ({$wpdb->posts}.ID = mt3.post_id)
        WHERE 1 = 1
            AND {$wpdb->posts}.post_type = 'coupon'
            AND ({$wpdb->posts}.post_status = 'publish')
            AND (
                {$wpdb->postmeta}.meta_key = 'cp_rate_metadata'
                AND (
                    mt1.meta_key = 'active_metadata'
                    AND CAST(mt1.meta_value AS CHAR) = 'active'
                )
                AND (
                    mt2.meta_key = 'store_coupon_metadata'
                    AND CAST(mt2.meta_value AS CHAR) = '$st_id'
                )
            )
        GROUP BY {$wpdb->posts}.ID
        ORDER BY {$wpdb->postmeta}.meta_value + 0 DESC ,{$wpdb->posts}.post_date DESC
        LIMIT 0, $limit
        ";
        $rs = $wpdb->get_row($query);
        if(count($rs) > 0)
            return array($rs->ID);
        else
            return null;
    }
    /**
     * GET UN-POPULAR COUPON BY STORE ID
     */
    function cpx_get_unpopular_coupons($store_id, $d = '', $show_expired = true, $rate_smaller = 50, $itemsToShow = 10)
    {
        global $wpdb;
        if(!$d)
            $d = date('y/m/d');
        if($show_expired)
                $query_show_expire = " OR ( mt2.meta_key = 'expire_date_metadata' AND CAST(mt2.meta_value AS DATE) < '{$d}' )";
        // Exclude top rate cp id
        $top_rate_cp = cpx_get_top_cp_rate($store_id);
        $not_in = "";
        if($top_rate_cp != null)
        {
            $id = $top_rate_cp[0];
            $not_in = "AND {$wpdb->posts}.ID != $id";
        }

        $query = "
            SELECT SQL_CALC_FOUND_ROWS {$wpdb->posts}.ID, {$wpdb->posts}.post_title
            FROM
                {$wpdb->posts}
                INNER JOIN {$wpdb->postmeta}
                    ON (
                        {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id
                    )
                INNER JOIN {$wpdb->postmeta} AS mt1
                    ON ({$wpdb->posts}.ID = mt1.post_id)
                INNER JOIN {$wpdb->postmeta} AS mt2
                    ON ({$wpdb->posts}.ID = mt2.post_id)
            WHERE 1 = 1
                AND {$wpdb->posts}.post_type = 'coupon'
                AND ({$wpdb->posts}.post_status = 'publish')
                AND (
                        {$wpdb->postmeta}.meta_key = 'store_coupon_metadata'
                        AND {$wpdb->postmeta}.meta_value = {$store_id}
                    )
                AND (
                    (
                        mt1.meta_key = 'cp_rate_metadata'
                        AND mt1.meta_value < {$rate_smaller}
                    )
                    {$query_show_expire}

                )
                $not_in
            GROUP BY {$wpdb->posts}.ID
            ORDER BY {$wpdb->posts}.post_date DESC
            LIMIT 0,{$itemsToShow} ;
            ";

            $rs = $wpdb->get_results($query);
            return $rs;
    }
    /**
     * HOOK TO SEARCH QUERY
     */
	function search_filter($query)
	{
		if ($query->is_main_query())
		{
			if ($query->is_search())
			{
                global $query;
                $kw = get_search_query();
                $limit = "LIMIT 0,99";
                $query = cpx_search_query_store($kw, $limit);
			}
		}
        return $query;
	}
    if(!is_admin())
        add_filter('pre_get_posts', 'search_filter');
    function cpx_search_query_store($keyword, $limit = "LIMIT 0,99")
    {
        global $wpdb;
        $query = "
                    SELECT
                        p.ID
                    FROM
                        {$wpdb->posts} AS p,
                        {$wpdb->postmeta} AS m
                    WHERE p.`ID` = m.`post_id`
                        AND p.`post_type` = 'store'
                        AND p.`post_status` = 'publish'
                        AND m.`meta_key` = 'view_store_metadata'
                        AND p.`post_title` LIKE '%$keyword%'
                    ORDER BY m.`meta_value` DESC $limit;
                ";
        return $query;
    }
    /**
     * HIGHLIGHT SEARCH KEYWORD
     */
    function cpx_remove_non_AlphaNumeric($string)
    {
        return preg_replace("/[^A-Za-z0-9 ]/", '', $string);
    }
    function cpx_highligh_keyword($text, $kw)
    {
        $kw = cpx_remove_non_AlphaNumeric($kw);
        $kw = explode(" ",$kw);
        $text = preg_replace('/(' . implode('|', $kw) . ')/iu', '<strong class="search-highlight-kw">\0</strong>',
		$text);
        echo $text;
    }
    /**
     * GET STORE DETAIL
     */
    function cpx_get_store_detail($store_id, $search_keyword = '')
    {
            $store_link = get_permalink($store_id);
            $store_url = get_post_meta($store_id,'url_store_metadata',true);
            $store_name = get_the_title($store_id);
            $store_des = get_post_field('post_content', $store_id);
            $store_des = truncate_str($store_des, 280);
            $store_logo = get_post_meta($store_id,'logo_metadata',true);
            if(!$store_logo)
                $store_logo = cpx_get_store_thumb($store_url);
    ?>
        <div class="row-fluid data-cp" >
                            <div class="span3 img-store">
                                    <a href="<?php echo $store_link; ?>">
                                        <div class="imgx">
                                        <img src="<?php echo $store_logo; ?>" alt="<?php echo $store_name; ?>" title="<?php echo $store_name; ?>" />
                                        <span class="seemore">See more Coupons</span>
                                        </div>
                                    </a>
                            </div>
                            <div class="span9 hotcoupon-info-store">
                                    <div class="row-fluid info-descrip">
                                        <h3 class="search-store-title"><a href="<?php echo $store_link; ?>" title="<?php echo $store_name; ?>"><?php echo($search_keyword != ''?cpx_highligh_keyword($store_name,$search_keyword):$store_name);?></a></h3>
                                        <p class="description">
                                        <?php echo $store_des; ?>
                                        </p>
                                    </div>
                                    <p class="merchantLink">
                                        <a href="<?php echo $store_link; ?>">Get <?php echo $store_name; ?> coupons &gt;&gt; </a>
                                    </p>
                            </div>
        </div>
        <hr/>
<?php }
    /**
     * Pagination
     */
    if (!function_exists('pagination'))
    {
        function pagination($pages = '', $range = 4) {
            $showitems = ($range * 2) + 1;
            global $paged;
            if (empty($paged))
                $paged = 1;
            if ($pages == '') {
                global $wp_query;
                $pages = $wp_query->max_num_pages;
                if (!$pages) {
                    $pages = 1;
                }
            }
            if (1 != $pages) {
                echo "<div class='pagination-event'>";
                echo "<div class=\"page_nav\">";
                if ($paged > 2 && $paged > $range + 1 && $showitems < $pages)
                    echo "<a title='First' href='" . get_pagenum_link(1) . "' class=\"prev page-numbers\">First</a>";
                if ($paged > 1 && $showitems < $pages)
                    echo "<a title='Previous' href='" . get_pagenum_link($paged - 1) . "' class=\"page-numbers dots\">&lsaquo;&lsaquo;</a>";
                for ($i = 1; $i <= $pages; $i++) {
                    if (1 != $pages && (!($i >= $paged + $range + 1 || $i <= $paged - $range - 1) || $pages <= $showitems )) {
                        echo ($paged == $i) ? "<span class=\"page-numbers current\">" . $i . "</span>" : "<a title='page-".$i."' href='" . get_pagenum_link($i) . "' class=\"page-numbers\">" . $i . "</a>";
                    }
                }
                if ($paged < $pages && $showitems < $pages)
                    echo "<a title='Next' href=\"" . get_pagenum_link($paged + 1) . "\" class=\"page-numbers dots\">&rsaquo;&rsaquo;</a>";
                if ($paged < $pages - 1 && $paged + $range - 1 < $pages && $showitems < $pages)
                    echo "<a title='Last' href='" . get_pagenum_link($pages) . "' class=\"next page-numbers\">Last</a>";
                echo "</div>\n";
                echo "</div>\n";
            }
        }
    }
        /**
     * Pagination custom query
     */
    if (!function_exists('pagination_custom'))
    {
        function pagination_custom($url,$page,$pages,$current,$range = 4) {
            $showitems = ($range * 2) + 1;
            echo "<div class=\"pagination-event\">";
                                echo "<div class=\"page_nav\">";
                                if($current != 1 && $showitems < $pages){
                                    echo "<a title='First' href='$url' class=\"prev page-numbers\">First</a>";
                                        if($current != 2 ){
                                            echo "<a title='Previous' href='$url?page=".($page-1)."' class=\"prev page-numbers\">&lsaquo;&lsaquo;</a>";
                                        }else{
                                            echo "<a title='Previous' href='$url' class=\"prev page-numbers\">&lsaquo;&lsaquo;</a>";
                                        }
                                }
                                for($i=1;$i<=$pages;$i++){
                                    if(1 != $pages && (!($i >= $page+$range+2 || $i<= $page-$range)|| $pages <= $showitems )){
                                        if($current != $i ){
                                            if($i == 1){
                                                echo "<a title='page-$i' href='$url' class=\"page-numbers\">$i</a>";
                                            }else{
                                                echo "<a title='page-$i' href='$url?page=$i' class=\"page-numbers\">$i</a>";
                                            }
                                        }else {
                                            echo "<span class=\"page-numbers current\">" . $i . "</span>";
                                        }
                                    }
                                }
                                if($current != $pages && $showitems < $pages){
                                    if($current != 1){
                                        echo "<a title='Next' href='$url?page=".($page+1)."' class=\"prev page-numbers\">&rsaquo;&rsaquo;</a>";
                                    }else{
                                        echo "<a title='Next' href='$url?page=".($page+2)."' class=\"prev page-numbers\">&rsaquo;&rsaquo;</a>";
                                    }
                                    echo "<a title='Last' href='$url?page=".($pages)."' class=\"prev page-numbers\">Last</a>";
                                }
                                echo "</div>\n";
                                echo "</div>\n";
        }
    }
    /**
     * GET RELATED STORES
     * @todo Get related stores
     * @return Array store ids
     */
    function cpx_get_relate_store($store_id, $itemsToShow)
    {
            // get stores have coupons
            $arr_st_have_cp = cpx_get_store_have_cp();
            // remove current store id from array
            $arr_st_have_cp = array_diff($arr_st_have_cp, array($store_id));
            // get the custom post type's taxonomy terms
            $custom_taxterms = wp_get_object_terms( $store_id, 'store_category', array('fields' => 'ids') );
            // arguments
            $args = array(
            'post_type' => 'store',
            'post_status' => 'publish',
            'posts_per_page' => $itemsToShow,
            'orderby' => 'rand',
            'tax_query' => array(
                array(
                    'taxonomy' => 'store_category',
                    'field' => 'id',
                    'terms' => $custom_taxterms
                )
            ),
            'post__in' => $arr_st_have_cp
            );

            $related_items = new WP_Query( $args );

            $arr_st_ids = array();
            if($related_items->have_posts())
            {
                foreach ($related_items->posts as $p) {
                    array_push($arr_st_ids, (int)$p->ID);
                }
            }
            return $arr_st_ids;
    }
    /**
     * GET LASTEST COUPON BY STORE ID
     * @todo "Get lastest coupons by coupon type"
     * @return Array coupon ids
     */
    function cpx_get_lastest_cp($itemsToShow, $coupon_type = '', $store_id = '')
    {
        $meta_query = array(
        array(
            'key' => 'active_metadata',
            'value' => 'active',
            'compare' => '=')
        );
        if($coupon_type)
        {
            $filter_by_cp_type = array(
            'key' => 'coupon_type_metadata',
            'value' => $coupon_type,
            'compare' => '=');
            array_push($meta_query, $filter_by_cp_type);
        }
        if($store_id)
        {
            $in_store = array(
			'key' => 'store_coupon_metadata',
			'value' => $store_id,
			'compare' => '=');
            array_push($meta_query, $in_store);
        }

        $args = array(
            'post_type' => 'coupon',
            'post_status' => 'publish',
            'meta_query' => $meta_query,
            'orderby' => 'date',
            'order' => 'DESC',
            'posts_per_page' => $itemsToShow);

        $query = new WP_Query($args);

        $arr_cp_ids = array();
        if($query->have_posts())
        {
            foreach ($query->posts as $p) {
                array_push($arr_cp_ids, (int)$p->ID);
            }
        }
        return $arr_cp_ids;
    }
    /**
     * GET STORES HAVE COUPONS
     * @return Array store ids
     */
    function cpx_get_store_have_cp()
    {
        global $wpdb;
        $qr = "SELECT meta_value AS 'ID' FROM {$wpdb->postmeta}  WHERE meta_key = 'store_coupon_metadata' GROUP BY meta_value;";
        $rs = $wpdb->get_results($qr);
        $arr_st_ids = array();
        if(count($rs) > 0)
        {
            foreach ($rs as $p) {
                array_push($arr_st_ids, $p->ID);
            }
        }
        return $arr_st_ids;
    }
    /**
     * GET TOP VIEW STORES
     */
    function cpx_get_top_view_stores($numberposts, $get_by = '')
    {
        $args = array(
        'post_type' => 'store',
        'post_status' => 'publish',
        'posts_per_page' => $numberposts,
        'meta_key' => 'view_store_metadata'
        );
        if($get_by)
            $args['orderby'] = 'rand';
        else
            $args['orderby'] = 'meta_value_num';

        $rs = new WP_Query($args);
        $arr_st_ids = array();
        if($rs->have_posts())
        {
            foreach ($rs->posts as $obj) {
                array_push($arr_st_ids, $obj->ID);
            }
        }
        return $arr_st_ids;
    }
    /**
     * GET AFF LINK HIT COUNT
     */
    function cpx_get_cp_hit_count($st_id)
    {
        global $wpdb;
        $qr = "select hitcount from {$wpdb->prefix}outlink where id = {$st_id}";
        $obj = $wpdb->get_row($qr);
        return $obj->hitcount;
    }

    function cpx_get_user_role_name()
    {
        $user = new WP_User(get_current_user_id());
        return array_shift($user->roles);
    }
    ini_set('max_execution_time', 99999);
	/**
	 * EMAIL SCHEDULE
	 */
//	if (get_option('email_schedule') == 1)
//	{
//		//schedule the send_email_new_coupons_daybyday event only once
//		if (!wp_next_scheduled('send_email_new_coupons_daybyday'))
//		{
//			wp_schedule_event(time(), 'daily', 'send_email_new_coupons_daybyday');
//		}
//		add_action('send_email_new_coupons_daybyday', 'do_action_send_email_to_subscribers');
//	}
//	else
//	{
//		// Remove schedule
//		wp_clear_scheduled_hook('send_email_new_coupons_daybyday');
//	}
//	function do_action_send_email_to_subscribers()
//	{
//		cpx_doaction_sendemail_daybyday();
//	}
	//    add_filter( 'cron_schedules', 'wi_add_weekly_schedule' );
	//    function wi_add_weekly_schedule( $schedules ) {
	//    	$schedules['five_minute'] = array(
	//    		'interval' => 60*5, //7 days * 24 hours * 60 minutes * 60 seconds
	//    		'display' => __( 'Once Minutes', 'mostcoupon.com' )
	//    	);
	//    	return $schedules;
	//    }
/*
 * Word Limiter
 */
        function word_limiter($str, $limit = 100, $end_char = '&#8230;') {
        if (trim($str) == '') {
            return $str;
        }
        preg_match('/^\s*+(?:\S++\s*+){1,' . (int) $limit . '}/', $str, $matches);
        if (strlen($str) == strlen($matches[0])) {
            $end_char = '';
        }
        return rtrim($matches[0]) . $end_char;
    }
    /*
     * Change Frefix Wordpress post permalink
     */
    function add_rewrite_rules( $wp_rewrite )
    {
            $new_rules = array(
                    'blog/(.+?)/?$' => 'index.php?post_type=post&name='. $wp_rewrite->preg_index(1),
            );

            $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
    }
    add_action('generate_rewrite_rules', 'add_rewrite_rules');

    function change_blog_links($post_link, $id=0){

            $post = get_post($id);

            if( is_object($post) && $post->post_type == 'post'){
                    return home_url('/blog/'. $post->post_name.'/');
            }

            return $post_link;
    }
    add_filter('post_link', 'change_blog_links', 1, 3);

    function twentythirteen_paging_nav() {
    global $wp_query;

    // Don't print empty markup if there's only one page.
    if ( $wp_query->max_num_pages < 2 )
        return;
    ?>
    <nav class="navigation paging-navigation" role="">
        <h1 class="screen-reader-text"><?php _e( 'Posts navigation', 'twentythirteen' ); ?></h1>
        <div class="nav-links">

            <?php if ( get_next_posts_link() ) : ?>
            <div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">&larr;</span> Older posts', 'twentythirteen' ) ); ?></div>
            <?php endif; ?>

            <?php if ( get_previous_posts_link() ) : ?>
            <div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">&rarr;</span>', 'twentythirteen' ) ); ?></div>
            <?php endif; ?>

        </div><!-- .nav-links -->
    </nav><!-- .navigation -->
    <?php
}
function the_breadcrumb() {
    global $post;

    if (!is_home()) {
        echo '<ul id="breadcrumbs">';
        echo '<li><a href="';
        echo get_option('home');
        echo '">';
        echo 'Home';
        echo '</a></li><li class="separator"> / </li>';
        if (is_category() || is_single()) {
            echo '<li>';
            the_category(' </li><li class="separator"> / </li><li> ');
            if (is_single()) {
                //echo '</li><li class="separator"> / </li><li>';
                the_title();
                echo '</li>';
            }
        } elseif (is_page()) {
            if($post->post_parent){
                $anc = get_post_ancestors( $post->ID );
                $title = get_the_title();
                foreach ( $anc as $ancestor ) {
                    $output = '<li><a href="'.get_permalink($ancestor).'" title="'.get_the_title($ancestor).'">'.get_the_title($ancestor).'</a></li> <li class="separator">/</li>';
                }
                echo $output;
                echo '<strong title="'.$title.'"> '.$title.'</strong>';
            } else {
                echo '<li>'.get_the_title().'</li>';
            }
        }
    echo '</ul>';
    }
    elseif (is_tag()) {single_tag_title();}
    elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y'); echo'</li>';}
    elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y'); echo'</li>';}
    elseif (is_year()) {echo"<li>Archive for "; the_time('Y'); echo'</li>';}
    elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';}
    elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';}
    elseif (is_search()) {echo"<li>Search Results"; echo'</li>';}

}